package com.elong.businesstravel.modules.orders;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.Base64Util;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.recorder.BaseRecordActivity;
import com.elong.businesstravel.base.recorder.Recorder;
import com.elong.businesstravel.base.recorder.UIMeterImageView;
import com.elong.businesstravel.base.recorder.listener.IRecordingStateListener;
import com.elong.businesstravel.entitys.OrderInfo;
import com.elong.businesstravel.protocol.order.AddcltreviewRequest;
import com.elong.businesstravel.protocol.order.AddcltreviewResponse;

/**
 * 发送语音评论界面
 * 
 * @author lenovo
 * 
 */
public class SendRecordCommentActivity extends BaseRecordActivity {

	private ViewGroup mPlayRecordLayout;
	private TextView mRecordLenghtTextView;
	private TextView mTipsTextView;
	private Button mRecordButton;
	private Button mSendButton;
	private ImageView mPlayAnimImageView;

	private Recorder mRecorder;
	private AnimationDrawable mAnimationDrawable;
	private OrderInfo mOrderInfo;

	@Override
	protected void onCreate(Bundle icycle) {
		super.onCreate(icycle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_send_record_comment);

		if (null == mSavedInstanceState) {
			mOrderInfo = (OrderInfo) getIntent().getSerializableExtra(
					"orderinfo");
		} else {
			mOrderInfo = (OrderInfo) mSavedInstanceState
					.getSerializable("orderinfo");
		}

		mTipsTextView = (TextView) findViewById(R.id.tipsTextView);
		mTipsTextView.setVisibility(View.INVISIBLE);
		mRecordLenghtTextView = (TextView) findViewById(R.id.recordLenghtTextView);
		mPlayRecordLayout = (ViewGroup) findViewById(R.id.playRecordLayout);
		mPlayRecordLayout.setVisibility(View.INVISIBLE);
		mPlayAnimImageView = (ImageView) findViewById(R.id.playAnimImageView);

		final UIMeterImageView uvMeter = (UIMeterImageView) findViewById(R.id.uvMeter);
		uvMeter.setVisibility(View.INVISIBLE);
		mRecordButton = (Button) findViewById(R.id.recordButton);
		setBaseMeterImageView(uvMeter, mRecordButton,
				new IRecordingStateListener() {

					@Override
					public void startRecordingUI() {
						DebugLog.logI("startRecordingUI");
						uvMeter.setVisibility(View.VISIBLE);
					}

					@Override
					public void with10SecondsLeftUI(final int progress) {
						DebugLog.logI("with10SecondsLeftUI");
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mTipsTextView.setText("录制时间还剩" + (progress)
										+ "秒");
								mTipsTextView.setVisibility(View.VISIBLE);
								if (0 == progress) {
									mTipsTextView.setText("录音完毕");
								}
							}
						});

					}

					@Override
					public void slideToCancelSendingUI() {
						DebugLog.logI("slideToCancelSendingUI");
					}

					@Override
					public void timeShortUI() {
						DebugLog.logI("timeShortUI");
						mTipsTextView.setText("时间太短！");
						mTipsTextView.setVisibility(View.VISIBLE);
					}

					@Override
					public void stopRecordingUI() {
						DebugLog.logI("stopRecordingUI");
						uvMeter.setVisibility(View.INVISIBLE);
						mTipsTextView.setVisibility(View.INVISIBLE);
					}

					@Override
					public void progressUI(int progress) {
						DebugLog.logI("progressUI : " + progress);

					}
				});

		Button deleteButton = (Button) findViewById(R.id.deleteButton);
		deleteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showDeleteRecordDialog();
			}
		});

		ViewGroup playLayout = (ViewGroup) findViewById(R.id.playLayout);
		playLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (null != mRecorder) {
					mRecorder.startPlayback();
					mAnimationDrawable = (AnimationDrawable) mPlayAnimImageView
							.getDrawable();
					mAnimationDrawable.start();
				}
			}
		});

		ImageView cancelImageView = (ImageView) findViewById(R.id.cancelImageView);
		cancelImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (null != mRecorder) {
					mRecorder.delete();
				}
				finish();
			}
		});

		mSendButton = (Button) findViewById(R.id.sendButton);
		mSendButton.setVisibility(View.GONE);
		mSendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (null != mRecorder) {
					addcltreview(mRecorder);
				}
			}
		});

	}

	@Override
	protected void sendRecorder(Recorder recorder) {
		mRecorder = recorder;
		mRecordLenghtTextView.setText((recorder.sampleLength()) + "”");
		mPlayRecordLayout.setVisibility(View.VISIBLE);
		mRecordButton.setVisibility(View.GONE);
		mSendButton.setVisibility(View.VISIBLE);
	}

	@Override
	public void onCompletion() {
		super.onCompletion();
//		HandlerToastUI.getHandlerToastUI(mContext, "播放完成");
		mAnimationDrawable.stop();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if(null != mAnimationDrawable){
			mAnimationDrawable.stop();
		}
	}

	private void deleteRecord() {
		if (null != mRecorder) {
			mRecorder.delete();
		}
		mPlayRecordLayout.setVisibility(View.INVISIBLE);
		mRecordButton.setVisibility(View.VISIBLE);
		mSendButton.setVisibility(View.GONE);
	}

	private void showDeleteRecordDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setMessage("是否删除当前语音评论");
		customAlertDialog.setLeftButton("删除", new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				deleteRecord();
			}
		});
		customAlertDialog.setRightButton("取消", new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});
		customAlertDialog.show();
	}

	private void addcltreview(final Recorder recorder) {
		showWaitDialog("正在上传请稍后...", new OnKeyCancel() {

			@Override
			public void onKeyCancelListener() {
				NetworkClient.getNetworkClient().cancelRequests(mContext, true);
			}
		});
		new Thread(new Runnable() {

			@Override
			public void run() {
				String redata = null;
				try {
					FileInputStream fileInputStream = new FileInputStream(
							recorder.getRecorderFile());
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					int len = -1;
					byte[] b = new byte[1024];
					try {
						while (-1 != (len = fileInputStream.read(b))) {
							byteArrayOutputStream.write(b, 0, len);
						}
						byteArrayOutputStream.flush();
						redata = Base64Util.encode(byteArrayOutputStream
								.toByteArray());
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							fileInputStream.close();
							byteArrayOutputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}

				OrderInfo orderInfo = mOrderInfo;
				NetworkClient.getNetworkClient().PostRequest(
						new AddcltreviewRequest(mContext,
								orderInfo.elongorderid, recorder.sampleLength()
										+ "", orderInfo.elonghotelid, redata),
						new AddcltreviewResponse() {
							@Override
							public void onResponse(
									ResponseHandlerInterface responseHandlerInterface) {
								HandlerPostUI.getHandlerPostUI(new Runnable() {

									@Override
									public void run() {

										if (0 != status) {
											HandlerToastUI.getHandlerToastUI(
													mContext, msg);
										} else {
											HandlerToastUI.getHandlerToastUI(
													mContext, "上传成功");
											int sampleLenght = recorder.sampleLength();
											deleteRecord();
											Intent intent = new Intent();
											intent.putExtra("voiceUrl", voiceUrl);
											intent.putExtra("voiceLenght", sampleLenght + "");
											setResult(RESULT_OK, intent);
											finish();
										}

										hideWaitDialog();
									}
								});
							}
						}, new BaseStateListener() {
						}, new BaseErrorListener() {
							@Override
							public void onFailure(int statusCode,
									Header[] headers, byte[] responseBody,
									Throwable error) {
								if (null != mContext
										&& mContext instanceof Activity) {
									StringBuffer stringBuffer = new StringBuffer();
									ErrorExceptionHandler
											.NetworkExceptionHandler(
													stringBuffer, error);
									if (!TextUtils.isEmpty(stringBuffer
											.toString())) {
										HandlerToastUI.getHandlerToastUI(
												mContext,
												stringBuffer.toString());
									}

								}
								HandlerPostUI.getHandlerPostUI(new Runnable() {

									@Override
									public void run() {
										hideWaitDialog();
									}
								});
							}

						});
			}
		}).start();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("orderinfo", mOrderInfo);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (null != savedInstanceState) {
			mOrderInfo = (OrderInfo) savedInstanceState
					.getSerializable("orderinfo");
		}
	}

}
